package com.stlm2.dems.user.service;

import com.stlm2.core.base.BaseDao;
import com.stlm2.core.base.impl.BaseServiceImpl;
import com.stlm2.core.redis.RedisClient;
import com.stlm2.dems.dao.ConfigDao;
import com.stlm2.dems.entity.Config;
import com.stlm2.dems.entity.FlowSource;
import com.stlm2.dems.entity.FlowType;
import com.stlm2.dems.entity.User;
import com.stlm2.dems.dao.FmsFlowDao;
import com.stlm2.dems.service.FmsFlowService;
import com.stlm2.dems.entity.OrderState;

import com.stlm2.dems.dao.TiXianShenQingDao;
import com.stlm2.dems.transfer.entity.Transfer;
import com.stlm2.dems.transfer.service.TransferService;
import com.stlm2.dems.user.dao.AccountDao;
import com.stlm2.dems.dao.UserDao;
import com.stlm2.dems.user.entity.*;
import com.stlm2.dems.service.UserService;
import com.stlm2.util.Convert;
import com.stlm2.util.PushUtil;
import com.stlm2.util.codecontent.CodeContent;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;


@Service("accountService")
@Transactional(rollbackForClassName={"java.lang.Exception"}, propagation = Propagation.REQUIRED)
public class AccountService extends BaseServiceImpl<Account> {

	@Resource
	private UserService userService;
	@Resource
	private AccountDao accountDao;
	@Resource
	private UserDao userDao;
	@Resource
	private TiXianShenQingDao tiXianShenQingDao;
	@Resource
	private FmsFlowDao fmsFlowDao;
	@Resource
	private ConfigDao configDao;

	@Resource
	private FmsFlowService fmsFlowService;
	@Resource
	private TransferService transferService;
	@Override
	protected BaseDao <Account> getDao() {
		return accountDao;
	}
    //通过用户id查询 资金账户
	public Account getByUserId(int userId){
		return  accountDao.getByUserId(userId);
	}
	public List<ModelMap> convert(List<Account> accounts) {
		List<ModelMap> list = new ArrayList<ModelMap>();
		if (accounts != null && accounts.size() > 0) {
			for (Account account : accounts) {
				ModelMap map = buildModel(account);
				list.add(map);
			}
		}
		return list;
	}

	public ModelMap buildModel(Account account) {
		ModelMap model = new ModelMap();
		if (account != null) {
			model.put("id", account.getId());
			model.put("accountState", account.getAccountState() != null ? account.getAccountState().toString() : "");
			model.put("accountStateValue", account.getAccountStateValue());
			model.put("userId", account.getUserId());
			model.put("accountKey", account.getAccountKey() != null ? account.getAccountKey() : "");
			model.put("accountMoney", account.getAccountMoney());
			model.put("accountType", account.getAccountType() != null ? account.getAccountType().toString() : "");
			model.put("accountTypeValue", account.getAccountTypeValue());
		}
		return model;
	}

    //已不再使用
	public String accountStatment(String token){
		ModelMap model=new ModelMap();
		//获得user对象
		User user=userDao.getByToken(token);
		if(user==null){
			return CodeContent.getModelByCode(-1,"",model);
		}
		if(user.getUserType()==null){
			return CodeContent.getModelByCode(0,"用户类型未设置",model);
		}
		model.put("userTypeValue",user.getUserTypeValue());
		model.put("userType",user.getUserType().toString());


			//累计订单金额
			model.put("order", 0);
			//累计做单金额
			model.put("shopOrder",0);

			//累计提现金额
			model.put("tiXianMoney",tiXianShenQingDao.countTiXianMoney(user.getId())!=null?tiXianShenQingDao.countTiXianMoney(user.getId()):0);
			//当前叮当
			Account account=accountDao.getByUserId(user.getId());

			//当前可用金额
			model.put("accountMoney",account.getAccountMoney());
		return CodeContent.getModelByCode(1,"",model);
	}

	public String transfer(Transfer transfer,String childId) {

		Account account=accountDao.getByUserId(transfer.getUserId());
		Account toAccount=accountDao.getByUserId(transfer.getToUserId());
		BigDecimal toMoney=transfer.getMoney();

		if(account==null&&toAccount==null&&toMoney==null)
			return CodeContent.returnFailure("缺失数据！");
		if(account.getAccountMoney().compareTo(toMoney)==-1)
			return CodeContent.returnFailure("积分不足，转帐失败！");



		account.setAccountMoney(account.getAccountMoney().subtract(toMoney));
		toAccount.setAccountMoney(toAccount.getAccountMoney().add(toMoney));


		updateEntity(account);
		updateEntity(toAccount);
		fmsFlowService.addFmsFlow(account.getUserId(),transfer.getCode(),toMoney, FlowSource.ZhuanZhang, FlowType.Reduce);
		fmsFlowService.addFmsFlow(toAccount.getUserId(),transfer.getCode(),toMoney,FlowSource.ZhuanZhang,FlowType.Add);
		transfer.setOrderState(OrderState.Payment);





		//推送消息
		Map<String,String> extras=new HashMap<String, String>();
		extras.put("type","transfer_in");
		extras.put("data",new JSONObject(transferService.buildModel(transfer)).toString());

		if(NumberUtils.isDigits(childId)){
			User childUser=userDao.getById(Integer.parseInt(childId));
			if(childUser!=null){
				transfer.setChildId(childUser.getId());
//				PushUtil.sendAlias("您的主店有一笔积分到帐！",childUser.getName(),null);
			}
		}
		transferService.updateEntity(transfer);

//		PushUtil.sendAlias("您有一笔积分到帐！",userDao.getById(transfer.getToUserId()).getName(),extras);

		extras.put("type","transfer_out");
//		PushUtil.sendAlias("您发起了一笔交易！",userDao.getById(transfer.getUserId()).getName(),extras);


		return CodeContent.returnSuccess(null);
	}


	public void  retPacket(){

	}


	public void  songJiFen_v2(){

	}
	class  Thread_v2 extends  Thread{
		List<Account> listO1 = new ArrayList<Account>();
		Thread_v2(List<Account> listParam){
			this.listO1 = listParam;

		}

		public void run() {

	               /*
	               *将每一个list的对象抽取出来进行，返积分等相关处理————直接调用一个dao层的接口就行了，传入一个user
	               * */

			JedisPool pool = null;
			Jedis jedis = null;
			try {
				pool = RedisClient.getPool();
				jedis = pool.getResource();
				for (Account account : listO1) {

					//判断账户的有效性,有效进行操作，无效不进行送积分操作
					if (AccountState.Normal.equals(account.getAccountState())) {

					}

				}

			}
			catch (Exception e){
				e.printStackTrace();
			}
			finally {
				pool.returnResource(jedis);
			}

		}
	}

    //将要发的红包金额随机拆分 对应的叮当总数个小红包
	public  int[] arr(int totalMoney, int cddNum){
		Random rand=new Random();
		int[] a=new int[cddNum];
		int k=totalMoney/cddNum;
		int m=totalMoney%cddNum;
		if(k==1){
			for(int i=0;i<cddNum ;i++){
				a[i]=1;
			}
			for (int i=0;i<m;i++){
				int j= rand.nextInt(cddNum);
				int temp=a[j];
				temp++;
				a[j]=temp;
			}
		}else {
			int v=k/2;
			int t=totalMoney-cddNum*v;
			for(int i=0;i<cddNum;i++){
				a[i]=v;
			}
			for(int i=0;i<t ;i++){
				int j= rand.nextInt(cddNum);
				int temp=a[j];
				temp++;
				a[j]=temp;
			}
		}
		return a;
	}
    //用户领取红包

    //用户领取后更新红包
	public  String updateMyRedPacket(String token){
		return CodeContent.getModelByCode(1,"",null);
	}




	public String  retPacketByMoney(){
		String msg="";
		ModelMap model=new ModelMap();
		model.put("msg",msg);
		return CodeContent.getModelByCode(1,"",model);
	}





}